package com.example.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sys.entity.Role;
import com.example.sys.entity.RoleMenu;
import com.example.sys.mapper.RoleMapper;
import com.example.sys.mapper.RoleMenuMapper;
import com.example.sys.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wuage
 * @since 2023-12-20
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
   @Resource
   private RoleMenuMapper roleMenuMapper;

    @Override
    @Transactional
    public void addRole(Role role) {
//        写入角色表
        this.baseMapper.insert(role);
//        写入角色菜单关系表
        if (null != role.getMenuIdList()){
            for(Integer menuId: role.getMenuIdList()){
                roleMenuMapper.insert(new RoleMenu(null,role.getRoleId(),menuId));
            }
        }
    }

    @Override
    public Role getRoleByID(Integer id) {
        Role role = this.baseMapper.selectById(id);
        List<Integer> menuIdList = roleMenuMapper.getMenuIdListByRoleId(id);
        role.setMenuIdList(menuIdList);
        return role;
    }

    @Override
    @Transactional
    public void updateRole(Role role) {
//        修改角色表
         this.baseMapper.updateById(role);
//        删除原有权限
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",role.getRoleId());
        roleMenuMapper.delete(wrapper);
//        新增权限
        if (null != role.getMenuIdList()){
            for(Integer menuId: role.getMenuIdList()){
                roleMenuMapper.insert(new RoleMenu(null,role.getRoleId(),menuId));
            }
        }
    }

    @Override
    @Transactional
    public void deleterole(Integer id) {
        this.baseMapper.deleteById(id);
        QueryWrapper<RoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",id);
        roleMenuMapper.delete(wrapper);
    }


}
